package sgi.misc;

import sgi.client.SGIInteractiveMapUI;
import sgi.details_new.ImageDetails;

import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.*;

import java.awt.event.MouseListener;

import processing.core.PApplet;
import de.fhpotsdam.unfolding.*;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.marker.Marker;
import de.fhpotsdam.unfolding.marker.SimplePointMarker;
import de.fhpotsdam.unfolding.providers.Microsoft;
import de.fhpotsdam.unfolding.ui.CompassUI;
import de.fhpotsdam.unfolding.utils.MapUtils;

import processing.core.PApplet;

import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;

import processing.core.PApplet;
/**The interactive map itself. Retrieves location list from server and populates an interactive map that's streamed from the web*/
public class InteractiveMapApplet extends PApplet implements ActionListener, ItemListener{

	UnfoldingMap map;
	
	JPopupMenu popup;
	//JButton btnBack, btnThisisbutton;
	JMenuItem menuItem1, menuItem2;
	GridBagLayout gridBagLayout;
	
	private int xCoord,yCoord;
	private int PAppSizeX = 800, PAppSizeY = 600;
	private List<ImageDetails> locationList;
	private Iterator<ImageDetails> locationIterator;
	private ImageDetails [] locationArray;
	CustomMarker [] markerArray;
	SGIInteractiveMapUI interactiveMapUI;
	
	Marker hitMarker;
	/**The constructor sets up the location array for use in population*/
	public InteractiveMapApplet(List<ImageDetails> list) {
		this.locationList = list;
		locationArray = new ImageDetails [list.size()];
		locationList.toArray(locationArray);
	}
	/**Sets the size and other parameters of the map, such as starting position and zoom level.
	 * Populates map with locations from database.*/
	@Override
	public void setup() {
		size(PAppSizeX,PAppSizeY);
		
		map = new UnfoldingMap(this);
		
		map.setTweening(true);
		map.setZoomRange(3f, 11f);
		//map.setPanningRestriction(UnfoldingMap.PRIME_MERIDIAN_EQUATOR_LOCATION, 40075/2f); //half of earth's circumference
		
		/**Show map around the location in the given zoom level*/
		map.zoomAndPanTo(UnfoldingMap.PRIME_MERIDIAN_EQUATOR_LOCATION, 3);
		//map.zoomAndPanTo(new Location(52.5f, 13.4f), 3);
		/** Add mouse and keyboard interactions*/
		MapUtils.createDefaultEventDispatcher(this, map);
		
		
		markerArray = new CustomMarker[locationArray.length];
		Location location;
		
		for (int i=0; i<locationArray.length; i++) {
			markerArray[i] = new CustomMarker(new Location(locationArray[i].getCoords().getX(),locationArray[i].getCoords().getY()));
			markerArray[i].setMarkerIndex(i); /**set marker id for O(1) searching*/
			//map.addMarker(markerArray[i]);
		}
		map.addMarkers(markerArray);
		
	}
	
	/**redraws and updates the map constantly.
	 * receives mouseover coordinates on the map and on the screen and draws map coordinates in the location of the mouse.*/
	public void draw() {
		map.draw();
		
		Location location = map.getLocation(mouseX, mouseY);
		fill(0);
		text(location.getLat() + ", " + location.getLon(), mouseX, mouseY);
		//btnThisisbutton.setVisible(true);
	}
	
	
	/*public InteractiveMapApplet() {
		// TODO Auto-generated constructor stub
	}*/
	@Override
	public void itemStateChanged(ItemEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	/**action listener for the Center Map button in the UI.
	 * If pressed will restore map to original location and zoom level*/
	@Override
	public void actionPerformed(ActionEvent evt) {
		if (evt.getActionCommand().equals("center map")) {
			map.zoomAndPanTo(UnfoldingMap.PRIME_MERIDIAN_EQUATOR_LOCATION, 3); //map.getZoomLevel());
		}
		
	}

/*	public void mousePressed(MouseEvent e) {
        maybeShowPopup(e);
    }

    public void mouseReleased(MouseEvent e) {
        maybeShowPopup(e);
    }
    
    private void maybeShowPopup(MouseEvent e) {
        if (e.isPopupTrigger()) {
            popup.show(e.getComponent(),
                       e.getX(), e.getY());
        }
    }*/
	
	/**mouse event listener for selecting/deselecting markers and activating UI buttons.
	 * sends marker info to the UI for show and sets up the purchase image/sample buttons*/
    public void mouseClicked() {
    	if (hitMarker!=null){ //deselect previously selected marker
      	  	hitMarker.setSelected(false);
      	  	hitMarker.setStrokeWeight(0);
      	  	interactiveMapUI.setInactive();
      	  	}
        hitMarker = map.getFirstHitMarker(mouseX, mouseY);
        if (hitMarker != null) {
            // Select current marker
            hitMarker.setSelected(true);
            hitMarker.setStrokeWeight(10);
            //((CustomMarker) hitMarker).getMarkerIndex();
            interactiveMapUI.setActive(locationArray[((CustomMarker) hitMarker).getMarkerIndex()]);
            //hitMarker.setColor(12);
        } 
        else {
            // Deselect all other markers
                interactiveMapUI.setInactive();
            
        }
    }
    
    
    /**Custom getSize as regular getSize doesn't work well with papplets*/
    public Dimension getCurrSize()
    {
    	Dimension dim = new Dimension(PAppSizeX,PAppSizeY);
		return dim;
    	
    }
    
    /**sets controller*/
    public void setController(SGIInteractiveMapUI interactiveMapUI) {
    	this.interactiveMapUI = interactiveMapUI;
    }

}
